#!/usr/bin/env python3
# -*- coding:utf-8 -*-
## author : cypro666
## date   : 2014.11.28
"""

"""
import sys, re
from os.path import realpath, dirname, basename, isdir
from collections import defaultdict

sys.path.append(dirname(dirname(realpath(__file__))))
from xbc3.debug import time_meter
from xbc3.fileio import FileIO
from xbc3.utilities import strip_url_param


class VLanCPVDistrib(object):
    """"""
    def __init__(self, *inputfiles):
        super().__init__()
        self.fn_bf = []
        for fn in inputfiles:
            if isdir(fn):
                continue
            if 'sys_bf_cpv' in  basename(fn):
                self.fn_bf.append(fn)
        if not self.fn_bf:
            print('Error:can not find sys_bf_cpv files!!!\n', file=sys.stderr)
            sys.exit()
        self.cpv_dict = defaultdict(lambda:defaultdict(lambda:0))
        self.vlan_dict = defaultdict(lambda:0)
        self.recpv = re.compile("""^.*?\|v:(\d+)\|cpv:(\d+)\|.*$""")
    
    def count_vlan_cpv(self, filename):
        file = FileIO(filename)
        for line in file:
            try:
                m = self.recpv.match(line)
                if not m:
                    continue
                v = int(m.group(1))
                self.vlan_dict[v] += 1
                c = int(m.group(2))
                self.cpv_dict[c][v] += 1
            except Exception as e:
                sys.stdout.write(str(e)+'\n')
        sys.stdout.write('%s finished, current len %d\n' % (filename, len(self.cpv_dict)))
    
    
    def output(self):
        """"""
        vlanlist = list(self.vlan_dict.keys())
        vlanlist.sort()
        sys.stdout.write('cpv, ')
        for v in vlanlist:
            sys.stdout.write('%d-n, %d-r, ' % (v, v))
        sys.stdout.write('\n')
        for c in sorted(self.cpv_dict, key=lambda k:sum(self.cpv_dict[k].values())):
            sys.stdout.write('%d, ' % c)
            d = self.cpv_dict[c]
            for v in vlanlist:
                if v in d:
                    sys.stdout.write('%d, %.3f%%, ' % (d[v], d[v]*100.0/self.vlan_dict[v]))
                else:
                    sys.stdout.write('0, 0.00%, ')
            sys.stdout.write('\n')


    @time_meter('VLanJsDistrib')
    def run(self):
        for fn in self.fn_bf:
            self.count_vlan_cpv(fn)
        self.output()
    


if __name__ == '__main__':
    '''driver'''
    inputfiles = []
    for line in sys.stdin:
        line = line.rstrip('\r\n')
        inputfiles.append(line)
    print(inputfiles)
    vcpv = VLanCPVDistrib(*inputfiles)
    vcpv.run()










